<!--
 * @Description: 学习视频列表
 * @Author: liyujie
 * @Date: 2021/10/16
 * @Last Modified by: liyujie
 * @Last Modified time: 2021/10/16
-->
<template>
    <PageLayout title="视频列表">
        <template slot="filter">
            <div class="filter-item">
                <el-radio-group
                    v-model="filterData.audit_status"
                    size="medium"
                    @change="getTableData(1)"
                >
                    <el-radio-button
                        v-for="item in verifyStatusList"
                        :key="item.value"
                        :label="item.value"
                    >
                        {{ item.label }}
                    </el-radio-button>
                </el-radio-group>
            </div>
            <div class="filter-item">
                <div class="filter-item__title">课程名称</div>
                <el-input
                    placeholder="请输入课程名称"
                    v-model="filterData.keyword"
                    suffix-icon="el-icon-search"
                    clearable
                    size="medium"
                    @change="getTableData(1)"
                    @keydown.enter.native="getTableData(1)"
                />
            </div>
            <div class="filter-item">
                <div class="filter-item__title">目录名称</div>
                <el-cascader
                    v-model="selectType"
                    clearable
                    filterable
                    size="medium"
                    :options="typeList"
                    :props="{
                        label: 'title',
                        value: 'no',
                        children: 'children',
                        checkStrictly: true
                    }"
                    @change="getTableData(1)"
                />
            </div>
            <div class="filter-item">
                <div class="filter-item__title">上架状态</div>
                <el-select
                    v-model="filterData.course_status"
                    filterable
                    clearable
                    size="medium"
                    @change="getTableData(1)"
                >
                    <el-option
                        v-for="item in statusList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </div>
            <div class="filter-item">
                <el-button
                    type="primary"
                    size="small"
                    class="query-button"
                    @click="getTableData(1)"
                >
                    查询
                </el-button>
            </div>
        </template>
        <el-table
            :data="tableData"
            height="100%"
            style="width: 100%;"
            ref="table"
            row-key="course_no"
            class="data-table"
            v-loading="tableLoading"
            @selection-change="handleSelectionChange"
        >
            <el-table-column
                type="selection"
                align="center"
                reserve-selection
                width="60"
            />
            <el-table-column
                prop="company_name"
                label="公司名称"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            />
            <el-table-column
                prop="course_name"
                label="课程名称"
                show-overflow-tooltip
            >
                <template slot-scope="{row}">
                    <div
                        class="link-text"
                        @click="previewVideo(row.file_url)"
                    >
                        {{ row.course_name }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                label="所属目录"
                show-overflow-tooltip
            >
                <template slot-scope="{row}">
                    {{ row.type_name }}<template v-if="row.sub_type_name"> - {{ row.sub_type_name }}</template>
                </template>
            </el-table-column>
            <el-table-column
                label="视频推广"
                width="150"
            >
                <template slot-scope="{row}">
                    <el-tooltip
                        effect="dark"
                        :content="row.recommend_title"
                        placement="top"
                        :disabled="row.recommend_title && row.recommend_title.length < 15"
                    >
                        <div
                            v-if="row.recommend_type"
                            class="link-text recommend"
                            @click="handleRecommendLink(row.recommend_type, row.recommend_no)"
                        >
                            <div class="recommend-title">
                                {{ row.recommend_type | recommendTypeFilter }}：{{ row.recommend_title }}
                            </div>
                        </div>
                        <div v-else>--</div>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column
                prop="course_view"
                label="真实浏览量"
                align="center"
            />
            <el-table-column
                prop="course_view_base"
                label="显示浏览量"
                align="center"
            />
            <el-table-column
                label="审核状态"
                align="center"
            >
                <template slot-scope="{row}">
                    <el-popover
                        placement="top"
                        width="200"
                        trigger="hover"
                        :disabled="row.audit_status !== -1"
                        :content="`驳回原因：${row.audit_reason}`"
                    >
                        <div
                            class="status-wrapper"
                            slot="reference"
                        >
                            <div
                                class="status-dot"
                                :class="['status-dot', row.audit_status === 0 ? 'warning' : row.audit_status === 1 ? 'success' : 'danger']"
                            />
                            <div>{{ row.audit_status | verifyFilter }}</div>
                        </div>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column
                label="上架状态"
                align="center"
            >
                <template slot-scope="{row}">
                    <el-switch
                        v-model="row.course_status"
                        :active-value="1"
                        :inactive-value="0"
                        @change="setCourseStatus(row)"
                    />
                </template>
            </el-table-column>
            <el-table-column
                label="创建时间"
                :formatter="emptyFormatter"
                width="150"
            >
                <template slot-scope="scope">
                    {{ scope.row.create_time * 1000 | dateFormatter('yyyy-MM-dd HH:mm:ss') }}
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                align="left"
                width="200"
                fixed="right"
            >
                <template slot-scope="{row}">
                    <div class="option-btn-group">
                        <el-button
                            type="text"
                            size="medium"
                            v-if="row.audit_status === 0"
                            @click="showVerifyDialog(row, 1)"
                        >
                            通过
                        </el-button>
                        <el-button
                            type="text"
                            size="medium"
                            v-if="row.audit_status === 0"
                            @click="showVerifyDialog(row, -1)"
                        >
                            驳回
                        </el-button>
                        <el-button
                            type="text"
                            size="medium"
                            v-if="row.audit_status === 0 || row.audit_status === 1"
                            @click="editCourse(row)"
                        >
                            编辑
                        </el-button>
                        <el-button
                            type="text"
                            size="medium"
                            style="color: #F95B56"
                            v-if="row.audit_status !== -2"
                            @click="handleDelete(row)"
                        >
                            删除
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <template slot="pagination">
            <div style="margin-left: 22px">
                <el-checkbox
                    label="当页全选"
                    v-model="checkAllStatus"
                    :indeterminate="checkIndeterminate"
                    :disabled="tableData.length === 0"
                    @change="handleSelectedAll"
                />
                <el-button
                    type="text"
                    size="medium"
                    style="margin-left: 12px"
                    :disabled="multipleSelection.length === 0"
                    @click="handleDeleteBatch()"
                >
                    批量删除
                </el-button>
                <el-button
                    type="text"
                    size="medium"
                    style="margin-left: 12px"
                    :disabled="multipleSelection.length === 0"
                    @click="changeTypeBatch"
                >
                    修改目录
                </el-button>
            </div>
            <el-pagination
                layout="total, prev, pager, next, jumper"
                background
                :current-page.sync="page.now_page"
                :total="page.total_count"
                :page-size="page.page_size"
                @current-change="getTableData"
            />
        </template>
    </PageLayout>
</template>

<script>
import {courseEditDialog} from '@/components/study-course/course-edit-dialog';
import {selectCourseTypeDialog} from '@/components/study-course/select-course-type';
export default {
    name: 'StudyCourseList',
    data() {
        return {
            filterData: {
                // 课程名称
                keyword: '',
                // 一二级分类
                type_no: '',
                sub_type_no: '',
                audit_status: 99,
                course_status: ''
            },
            tableData: [],
            tableLoading: false,
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 20
            },
            verifyStatusList: [
                { label: '全部', value: 99 },
                { label: '待审核', value: 0 },
                { label: '已通过', value: 1 },
                { label: '已驳回', value: -1 },
            ],
            statusList: [
                { label: '全部', value: '' },
                { label: '上架', value: 1 },
                { label: '下架', value: 0 },
            ],
            selectType: [],
            typeList: [],
            checkAllStatus: false,
            checkIndeterminate: false,
            multipleSelection: []
        };
    },
    filters: {
        verifyFilter(val) {
            switch (val) {
                case 0:
                    return '待审核';
                case 1:
                    return '已通过';
                case -1:
                    return '已驳回';
                case -2:
                    return '已删除';
                default:
                    return '--';
            }
        },
        recommendTypeFilter(val) {
            switch (val) {
                case 1:
                    return '职位名称';
                case 2:
                    return '任务标题';
                case 3:
                    return '商品名称';
                case 4:
                    return '店铺推广';
                default:
                    return '--';
            }
        },
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            this.$store.commit('SET_HEADER', [{title: "APP后台"}, {title: '学习'}, {title: '课程列表'}]);
            let filterData = JSON.parse(sessionStorage.getItem('STUDY_COURSE_QUERY'));

            if (filterData) {
                this.filterData = filterData;
                this.page.now_page = Number(sessionStorage.getItem('STUDY_COURSE_PAGE_NO'));
                sessionStorage.removeItem('STUDY_COURSE_QUERY');
                sessionStorage.removeItem('STUDY_COURSE_PAGE_NO');
            }
            this.getTableData();
            this.getTypeList();
            this.authResult = this.$route.meta.authResult;
        },

        /**
         * @description 获取列表数据
         * @param page
         */
        getTableData(page) {
            this.tableLoading = true;
            let params = { ...this.filterData };

            params.page_id = page || this.page.now_page;
            params.type_no = this.selectType[0];
            params.sub_type_no = this.selectType[1];
            this.$post('/student/course%5Cget_list', params, res => {
                if (res.code === 1) {
                    this.tableData = res.data.list;
                    this.page = res.data.page;
                } else {
                    this.$notify({
                        title: '提示',
                        type: 'warning',
                        message: res.msg
                    });
                }
                this.tableLoading = false;
            });
        },

        /**
         * @description 获取目录级联
         */
        getTypeList() {
            this.$post('/student/course_type%5Cget_list_linkage', {}, res => {
                if (res.code === 1) {
                    this.typeList = res.data.list;
                } else {
                    this.$notify({
                        title: '提示',
                        type: 'warning',
                        message: res.msg
                    });
                }
            });
        },

        /**
         * 路由跳转
         * @param routeName
         * @param query
         * @param auth_name
         */
        handleRoute(routeName, query, auth_name) {
            if(auth_name && !this.authResult[auth_name]) {
                this.$notify({
                    title: '提示',
                    message: '请联系管理员添加权限',
                    type: 'warning',
                    duration: 2000
                });
                return false;
            }
            this.$router.push({
                name: routeName,
                query
            });

            sessionStorage.setItem('STUDY_COURSE_QUERY', JSON.stringify(this.filterData));
            sessionStorage.setItem('STUDY_COURSE_PAGE_NO', this.page.now_page);
        },

        /**
         * @description 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) return '--';
            return val;
        },

        /**
         * 预览视频
         * @param url
         */
        previewVideo(url) {
            if(!url) {
                this.$message.warning('视频地址为空');
                return;
            }

            window.open(url, 'videoPreview');
        },

        /**
         * 设置上下架状态
         * @param row
         */
        setCourseStatus(row) {
            if(!this.authResult.auth_set_status) {
                this.$notify({
                    title: '提示',
                    message: '请联系管理员添加权限',
                    type: 'warning',
                    duration: 2000
                });
                return false;
            }
            let params = {
                course_no: row.course_no,
                course_status: row.course_status
            };

            this.$post('/student/course%5Cmodify', params, resp => {
                if (resp.code === 1) {
                    this.getTableData();
                    this.$notify({
                        title: '提示',
                        type: 'success',
                        message: '操作成功'
                    });
                } else {
                    this.$notify({
                        title: '提示',
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },

        /**
         * 显示审核操作弹窗
         * @param row
         * @param action
         */
        async showVerifyDialog(row, action) {
            if(!this.authResult.auth_verify) {
                this.$notify({
                    title: '提示',
                    message: '请联系管理员添加权限',
                    type: 'warning',
                    duration: 2000
                });
                return false;
            }

            if (action === 1) {
                this.$zdConfirm('确认课程审核通过？', '温馨提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    await this.handleVerify(row.course_no, action);
                }).catch(() => {});
            } else {
                let reason = await this.$zdPrompt({
                    title: '课程审核不通过',
                    message: '不通过原因',
                    placeholder: '请输入不通过原因…'
                });

                if(reason) {
                    await this.handleVerify(row.course_no, action, reason);
                }
            }
        },

        /**
         * 审核
         * @param course_no
         * @param audit_status
         * @param audit_reason
         */
        async handleVerify(course_no, audit_status, audit_reason = '') {
            let data = await this.getDetail(course_no);
            let params = {
                ...data,
                audit_status,
                audit_reason,
            };

            this.$post('/student/course%5Caudit', params, resp => {
                if (resp.code === 1) {
                    this.$notify({
                        title: '提示',
                        message: '操作成功',
                        duration: 2000,
                        type: 'success'
                    });
                    this.getTableData();
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        duration: 2000,
                        type: 'warning'
                    });
                }
            });
        },

        /**
         * 获取详情
         * @param course_no
         */
        getDetail(course_no) {
            return new Promise((resolve, reject) => {
                this.$post('/student/course%5Cget', {course_no}, resp => {
                    if (resp.code === 1) {
                        resolve(resp.data);
                    } else {
                        this.$notify({
                            title: '提示',
                            message: resp.msg,
                            duration: 2000,
                            type: 'warning'
                        });
                    }
                });
            });

        },

        /**
         * 删除
         * @param row
         */
        handleDelete(row) {
            if(!this.authResult.auth_delete) {
                this.$notify({
                    title: '提示',
                    message: '请联系管理员添加权限',
                    type: 'warning',
                    duration: 2000
                });
                return false;
            }
            this.$zdConfirm('是否删除已选中课程？课程删除后不可恢复，请谨慎操作', '温馨提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let params = {
                    course_no: row.course_no
                };

                this.$post('/student/course%5Cdelete', params, resp => {
                    if (resp.code === 1) {
                        this.$notify({
                            title: '提示',
                            message: '删除成功',
                            duration: 2000,
                            type: 'success'
                        });
                        this.getTableData();
                    } else {
                        this.$notify({
                            title: '提示',
                            message: resp.msg,
                            duration: 2000,
                            type: 'warning'
                        });
                    }
                });
            }).catch(() => {});
        },

        /**
         * 批量删除
         */
        handleDeleteBatch() {
            if(!this.authResult.auth_delete_batch) {
                this.$notify({
                    title: '提示',
                    message: '请联系管理员添加权限',
                    type: 'warning',
                    duration: 2000
                });
                return false;
            }
            this.$zdConfirm('是否删除已选中课程？课程删除后不可恢复，请谨慎操作', '温馨提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let params = {
                    course_nos: this.multipleSelection.map(item => {
                        return item.course_no;
                    }).join()
                };

                this.$post('/student/course%5Cdelete_batch', params, resp => {
                    if (resp.code === 1) {
                        this.$notify({
                            title: '提示',
                            message: '删除成功',
                            duration: 2000,
                            type: 'success'
                        });
                        this.getTableData();
                        this.$refs.table.clearSelection();
                    } else {
                        this.$notify({
                            title: '提示',
                            message: resp.msg,
                            duration: 2000,
                            type: 'warning'
                        });
                    }
                });
            }).catch(() => {});
        },

        /**
         * 编辑课程
         * @param row
         */
        async editCourse(row) {
            if(!this.authResult.auth_edit) {
                this.$notify({
                    title: '提示',
                    message: '请联系管理员添加权限',
                    type: 'warning',
                    duration: 2000
                });
                return false;
            }
            let result = await courseEditDialog({
                courseNo: row.course_no,
                rowStatus: row.audit_status,
                typeList: this.typeList,
                _parent: this
            });

            if(result) this.getTableData();
        },


        /**
         * 点击全选
         * @param val
         */
        handleSelectedAll(val) {
            if(val) {
                this.$refs.table.toggleAllSelection();
            } else {
                this.$refs.table.clearSelection();
            }
            this.checkIndeterminate = false;
        },

        /**
         * 选中
         * @param selection
         */
        handleSelectionChange(selection) {
            let checkedCount = selection.length;

            this.multipleSelection = selection;
            this.checkAllStatus = checkedCount === this.tableData.length;
            this.checkIndeterminate = checkedCount > 0 && checkedCount < this.tableData.length;
        },

        /**
         * 批量修改目录
         */
        async changeTypeBatch() {
            let result = await selectCourseTypeDialog({
                title: '修改目录',
                typeList: this.typeList
            });

            if(result) {
                let params = {
                    course_nos: this.multipleSelection.map(item => {
                        return item.course_no;
                    }).join(),
                    type_no: result
                };

                this.$post('/student/course%5Cmove_batch_course', params, resp => {
                    if (resp.code === 1) {
                        this.$notify({
                            title: '提示',
                            message: '操作成功',
                            duration: 2000,
                            type: 'success'
                        });
                        this.getTableData();
                        this.$refs.table.clearSelection();
                    } else {
                        this.$notify({
                            title: '提示',
                            message: resp.msg,
                            duration: 2000,
                            type: 'warning'
                        });
                    }
                });
            }
        },

        /**
         * 跳转推广
         * @param type
         * @param no
         */
        handleRecommendLink(type, no) {
            // 招聘
            if(type === 1) {
                let routeData = this.$router.resolve({
                    name: 'recruitPostList',
                    query: {recruit_no: no}
                });

                window.open(routeData.href, '_blank');
            }

            // 远程任务
            if(type === 2) {
                let routeData = this.$router.resolve({
                    name: 'shopProjectApplyList',
                    query: {task_no: no}
                });

                window.open(routeData.href, '_blank');
            }

            // 商品
            if(type === 3) {
                let routeData = this.$router.resolve({
                    name: 'GoodsList',
                    query: {goods_no: no}
                });

                window.open(routeData.href, '_blank');
            }

            // 店铺
            if(type === 4) {
                let routeData = this.$router.resolve({
                    name: 'ShopList',
                    query: {shop_no: no}
                });

                window.open(routeData.href, '_blank');
            }
        }
    }
};
</script>

<style scoped lang="less">
.link-text {
    color: #20A0FF;
    cursor: pointer;
    text-overflow: ellipsis;
    overflow: hidden;
    &.recommend {
        .recommend-title {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            cursor: pointer;
            line-height: 20px;
            overflow: hidden;
            text-overflow: ellipsis;
            display:-webkit-box;
            -webkit-line-clamp: 2;
            /*! autoprefixer: off */
            -webkit-box-orient: vertical;
        }
    }
}
</style>
